#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<string.h>
#include<fcntl.h>
int main()
{
while(1)
{
printf("[user@host path]$ ");
fflush(stdout);
char input[1024]={0};
fgets(input,1023,stdin);
input[strlen(input)-1]='\0';
char* argv[32]={NULL};
int argc=0;
argv[argc]=strtok(input," ");
while(argv[argc]!=NULL)
{
argv[++argc]=strtok(NULL," ");
}
if(strcmp(argv[0],"cd")==0)
{
chdir(argv[1]);
}

int flag=0;
char *redirect=NULL;
int i;
for(i=0;i<argc;++i)
{
if(strcmp(argv[i],">")==0)
{
flag=1;if(i+1>argc){printf("格式错误\n");continue;}
redirect=argv[i+1];
argv[i]=NULL;
break;
}else if(strcmp(argv[i],">>")==0)
{
flag=2;if(i+1>argc){printf("格式错误\n");continue;}
redirect=argv[i+1];
argv[i]=NULL;
break;
}

}



pid_t child=fork();
if(child<0)
{
perror("fork error");
continue;
}else if(child==0)
{
if(flag==1)
{
int fd=open(redirect,O_WRONLY|O_CREAT|O_TRUNC,0664);
dup2(fd,1);
}else if(flag==2)
{
int fd=open(redirect,O_WRONLY|O_CREAT|O_APPEND,0664);
dup2(fd,1);
}

execvp(argv[0],argv);
exit(-1);
}

wait(NULL);
}
return 0;
}


